package com.mlnx.bptp.util;

/**
 * 16进制与BYTE转换
 *
 * @author zzb
 * @create 2019/3/14 8:57
 */
public class TurnByte {

    /**
     * 字节转十六进制
     * @param b 需要进行转换的byte字节
     * @return  转换后的Hex字符串
     */
    public static String byteToHex(byte b){
        String hex = Integer.toHexString(b & 0xFF);
        if(hex.length() < 2){
            hex = "0" + hex;
        }
        return hex;
    }


    /**
     * 字节数组转16进制
     * @param bytes 需要转换的byte数组
     * @return  转换后的Hex字符串
     */
    public static String bytesToHex(byte[] bytes) {
        StringBuffer sb = new StringBuffer();
        for(int i = 0; i < bytes.length; i++) {
            String hex = Integer.toHexString(bytes[i] & 0xFF);
            if(hex.length() < 2){
                sb.append(0);
            }
            sb.append(hex);
        }
        return sb.toString();
    }


    /**
     * Hex字符串转byte
     * @param inHex 待转换的Hex字符串
     * @return  转换后的byte
     */
    public static byte hexToByte(String inHex){
        return (byte)Integer.parseInt(inHex,16);
    }

    public static byte[] hexToByteArray(String inHex){
        int hexlen = inHex.length();
        byte[] result;
        if (hexlen % 2 == 1){
            //奇数
            hexlen++;
            result = new byte[(hexlen/2)];
            inHex="0"+inHex;
        }else {
            //偶数
            result = new byte[(hexlen/2)];
        }
        int j=0;
        for (int i = 0; i < hexlen; i+=2){
            result[j]=hexToByte(inHex.substring(i,i+2));
            j++;
        }
        return result;

    }
    public static void main(String[] args) throws Exception{

//        byte[] bytes="777".getBytes();
//        System.out.println(TurnByte.bytesToHex(bytes));
//        int code =0xff;
//        System.out.println(code);


        byte[] b={(byte)0xFA ,(byte)0x09 ,(byte)0x40 ,(byte)0x00,(byte)0x00,
                (byte)0x00 ,(byte)0x00};
//        int p[] = {0x000000ff & 0xFA, 0x000000ff & 0x06, 0x000000ff & 0xa3, 0x000000ff & 0x03,};
//        int pp[]=new int[b.length];
//        for(int i=0;i<b.length;i++){
//            pp[i]=0x000000ff &b[i];
//        }

        System.out.println("mlnx345678".getBytes().length);
        String body = new String("mlnx345678".getBytes(), "utf-8");
        System.out.println(body);
//        System.out.println(ByteBufUtil.hexDump(d)+"==========");
//        System.out.println(Integer.toHexString(gg[0])+","+""+gg[1]);
//        int sbp = 0x000000ff & b[1];
//        System.out.println(sbp);


//        ByteBuf buf = Unpooled.copiedBuffer(b);
//        byte[] req = new byte[buf.readableBytes()];
//        buf.readBytes(req);
//        System.out.println(req+"====================");
//
//        System.out.println(Unpooled.copiedBuffer(b));
////        System.out.println(TurnByte.bytesToHex(b).getBytes().length);
//        String str= new String (b);
//
//
//
//        String body = new String(b, "utf-8");
//        System.out.println("Client :" + body );
    }
}
